<template>
  <div v-if="dialogShow" v-loading="loading" :element-loading-text="loadingText">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="goBack">区域面积占比配置</el-breadcrumb-item>
        <el-breadcrumb-item>{{ formData.id ? (flag === 'edit' ? '编辑' : '详情') : '新增' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="qup-title-box">
      <span class="border" /><span>适用面积信息</span>
    </div>
    <div style="margin-bottom: 10px">
      <el-button v-if="!isEditForm && flag !== 'detail'" type="primary" size="mini" @click="handleEditForm">编辑</el-button>
      <div v-if="isEditForm">
        <el-button type="primary" size="mini" @click="handleSaveInfo">保存</el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </div>
    </div>
    <el-form ref="ruleForm" :model="formData" size="mini" :rules="rules" label-width="120px">
      <el-row class="form_item_height">
        <el-col :xs="8" :sm="8" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用最小面积:" prop="suitMinarea">
            <span v-if="flag === 'detail' || !isEditForm">{{ formData.suitMinarea }}</span>
            <el-input v-else v-model.number="formData.suitMinarea" placeholder="请输入适用最小面积" @change="checkMinArea" />
          </el-form-item>
        </el-col>
        <el-col :xs="8" :sm="8" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用最大面积:" prop="suitMaxarea">
            <span v-if="flag === 'detail' || !isEditForm">{{ formData.suitMaxarea }}</span>
            <el-input v-else v-model.number="formData.suitMaxarea" placeholder="请输入适用最大面积" @change="checkMaxArea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <div class="qup-title-box">
        <span class="border" /><span>区域占比明细</span>
      </div>
      <div v-if="flag !== 'detail'" class="btn-group">
        <el-button v-if="showPageFlag" type="primary" size="mini" @click="editRow">编辑</el-button>
        <el-button v-if="!showPageFlag" type="primary" size="mini" @click="addRow">新增</el-button>
        <!-- <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleImport">导入</el-button> -->
        <!-- <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleExport">导出</el-button> -->
        <el-button v-if="!showPageFlag" type="primary" size="mini" @click="handleDel">删除</el-button>
        <!-- <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleChangeStatus(1)">启用</el-button> -->
        <!-- <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleChangeStatus(0)">停用</el-button> -->
        <!-- <el-button v-if="!showPageFlag && isEditTable" type="primary" size="mini" @click="saveEditRow">保存编辑</el-button> -->
        <el-button v-if="!showPageFlag" type="primary" size="mini" @click="saveNewRow">保存</el-button>
        <el-button v-if="!showPageFlag" type="primary" size="mini" @click="cancelEdit">取消</el-button>
      </div>
      <el-table
        ref="refTable"
        v-loading="tableLoading"
        element-loading-text="加载中"
        :data="tableData"
        highlight-current-row
        max-height="400"
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%; margin-top: 20px"
        @selection-change="selectionChangeHandle"
      >
        <!-- :selectable="selectable" -->
        <el-table-column v-if="flag !== 'detail'" type="selection" width="55" />
        <el-table-column prop="specialAreaType" label="区域分类" min-width="100">
          <template slot="header">
            <span style="color: red">*</span>区域分类
          </template>
          <template slot-scope="scope">
            <span v-if="flag === 'detail' || !scope.row.addFlag">{{ formaterData(belongRegionClassList, scope.row.specialAreaType) }}</span>
            <c-dict-select v-if="scope.row.addFlag" v-model="scope.row.specialAreaType" dict-type-code="BELONG_REGION_CLASS" placeholder="区域分类" @change="changeAreaType(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="areaRatio" label="面积占比" min-width="100">
          <template slot="header">
            <span style="color: red">*</span>面积占比(%)
          </template>
          <template slot-scope="scope">
            <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.areaRatio }}</span>
            <el-input v-else v-model.number="scope.row.areaRatio" type="number" size="mini" min="1" @blur="handelBlur(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="explains" label="说明" min-width="100">
          <template slot-scope="scope">
            <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.explains }}</span>
            <el-input v-else v-model="scope.row.explains" size="mini" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getProportionForm, getProportionDetail, saveProportionDetail, putProportionDetail, saveProportionForm } from '@/api/basicData'
import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'AddProportion',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      loading: false,
      loadingText: '',
      flag: '',
      showPageFlag: true,
      isEditForm: false,
      tableLoading: false,
      oldFormInfo: {},
      belongRegionClassList: [],
      seriesNameList: [],
      enableList: [
        { dictName: '启用', dictCode: 1 },
        { dictName: '停用', dictCode: 0 }
      ],
      selectedRows: [],
      tableConfig: {
        pageFlag: true,
        hideFuncBar: true,
        setting: []
      },
      formData: {
        configSpace: [],
        enable: 1
      },
      rules: {
        suitMinarea: [{ required: true, message: '请输入适用最小面积' }],
        suitMaxarea: [{ required: true, message: '请输入适用最大面积' }]
      },
      dataId: [],
      tableData: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  async created() {
    await this.getDictByPatchTypeAll(['BELONG_REGION_CLASS']).then(res => {
      this.belongRegionClassList = res.BELONG_REGION_CLASS
    })
    if (this.detailData.id) {
      this.loading = false
      this.loadingText = '加载中'
      this.flag = this.detailData.flag
      await this.getFormData()
      await this.getTableData()
    }
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    formaterArr(dictList, str) {
      if (!str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      dictList.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    convertDataFormat(str) {
      if (!str || !str.length) return
      const arr = str.split(',')
      return arr
    },
    // 多选框是否可选
    selectable(row) {
      if (!this.showPageFlag) {
        if (row.id) {
          return false
        }
        return true
      }
      return true
    },
    // 获取表单数据
    async getFormData() {
      this.loading = true
      this.loadingText = '加载中'
      await getProportionForm(this.detailData.id).then(res => {
        if (res.success && res.data) {
          this.formData = res.data
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    // 获取表格数据
    async getTableData() {
      this.tableLoading = true
      const otherFilter = [{ 'id': 'configAreaRatioId', 'property': 'configAreaRatioId', 'operator': '=', 'value': this.formData.id }]
      const dataForm = new FormData()
      dataForm.append('onlyCountFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(otherFilter))
      await getProportionDetail(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.tableData.forEach(item => {
            this.$set(item, 'editFlag', false)
          })
        }
        this.tableLoading = false
        this.showPageFlag = true
        this.isEditTable = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 切换区域类型
    changeAreaType(row) {
      this.$nextTick(() => {
        const specialAreaType = row.specialAreaType
        const tmp = this.belongRegionClassList.filter(item => item.dictCode === specialAreaType)
        const arr = this.tableData.filter(item => item.specialAreaType === specialAreaType)
        if (arr.length > 1) {
          this.$message.warning(`【${tmp[0].dictName}】区域分类已存在，请勿重复选择`)
          this.$set(row, 'specialAreaType', '')
        }
      })
    },
    // 面积
    handelBlur(row) {
      const num = Number(row.areaRatio)
      if (isNaN(num) || num < 1 || (num % 1 !== 0) || num > 100) {
        row.areaRatio = ''
        this.$message.warning('请输入1~100的整数')
      }
    },
    // 比较适用面积
    checkMinArea(value) {
      const area = value
      if (isNaN(area) || area < 0 || (area % 1 !== 0)) {
        this.$message.warning('请输入大于或等于0的整数')
        this.formData.suitMinarea = ''
        return
      }
      if (Number(value) > Number(this.formData.suitMaxarea)) {
        this.$message.warning('适用最小面积不可大于适用最大面积，请重新输入')
        value = ''
        this.formData.suitMinarea = ''
      }
    },
    // 比较适用面积
    checkMaxArea(value) {
      const area = value
      if (isNaN(area) || area < 0 || (area % 1 !== 0)) {
        this.$message.warning('请输入大于或等于0的整数')
        this.formData.suitMaxarea = ''
        return
      }
      if (Number(value) < Number(this.formData.suitMinarea)) {
        this.$message.warning('适用最小面积不可大于适用最大面积，请重新输入')
        value = ''
        this.formData.suitMaxarea = ''
      }
    },
    // 编辑表单
    handleEditForm() {
      this.oldFormInfo = JSON.parse(JSON.stringify(this.formData))
      this.isEditForm = true
    },
    // 取消编辑表单
    cancel() {
      this.formData = JSON.parse(JSON.stringify(this.oldFormInfo))
      this.isEditForm = false
      this.$refs.ruleForm.clearValidate()
    },
    // 编辑表格数据
    editRow() {
      // if (!this.tableData.length) {
      //   this.$message.warning('当前不存在可编辑数据')
      //   return
      // }
      this.tableData.forEach(item => {
        item.editFlag = true
      })
      this.isEditTable = true
      this.showPageFlag = false
    },
    // 新增
    addRow() {
      this.showPageFlag = false
      const obj = {
        areaRatio: '',
        explains: '',
        specialAreaType: '',
        configAreaRatioId: this.formData.id,
        editFlag: true,
        addFlag: true
      }
      this.tableData.unshift(obj)
      this.showSaveBtn = false
      this.showPageFlag = false
      this.isEditTable = false
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    // 导入成功
    handleImportSuccess() {
      this.getTableData()
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 删除
    handleDel() {
      if (this.selectedRows.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // this.tableLoading = true
        // const arr = this.selectedRows.filter(item => item.id)
        // if (!arr.length) {
        if (this.selectedRows.length === this.tableData.length) {
          this.selectedRows = []
          this.tableData = []
          this.$refs.refTable.clearSelection()
        } else {
          const tmpData = this.tableData.filter(row => {
            const index = this.selectedRows.findIndex(v => v.specialAreaType === row.specialAreaType)
            return index === -1
          })
          this.tableData = tmpData
          // this.selectedRows = []
          this.$refs.refTable.clearSelection()
        }
        // return
        // }
        // this.tableLoading = true
        // this.selectedRows.forEach(item => { item.dr = 1 })
        // const ids = this.selectedRows.map(item => item.id)
        // await delProportionDetail(ids).then(async res => {
        //   if (res.success) {
        //     this.$message.success('删除成功')
        //     await this.getTableData()
        //     this.editRow()
        //   }
        //   this.tableLoading = false
        // }).catch(() => {
        //   this.tableLoading = false
        // })
      })
    },
    // 取消编辑表格
    cancelEdit() {
      this.getTableData()
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 返回
    goBack() {
      if (this.isEditForm || !this.showPageFlag) {
        // this.$confirm('存在未保存数据，是否确认取消并返回列表界面?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        this.$message.warning('当前页面存在为保存的数据')
        return
        // this.dialogShow = false
        // this.isEditTable = false
        // this.clearForm()
        // this.$emit('goBack')
        // })
      }
      // else {
      this.dialogShow = false
      this.isEditTable = false
      this.clearForm()
      this.$emit('goBack')
      // }
    },
    clearForm(done) {
      this.formData = { belongRegion: 'Q001' }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 保存表单
    handleSaveInfo() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.loadingText = '系统处理中'
          saveProportionForm(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.isEditForm = false
              this.getFormData()
            }
            this.loading = false
            this.loadingText = ''
          }).catch(() => {
            this.loading = false
            this.loadingText = ''
          })
        }
      })
    },
    // 保存表格--新增
    saveNewRow() {
      if (this.submiting) return
      if (!this.tableData.length) {
        this.$message.warning('请添加区域占比明细数据')
        return
      }
      const flag = this.tableData.some(item => !item.specialAreaType || !item.areaRatio)
      if (flag) {
        this.$message.warning('请完善表格数据')
        return
      }
      let area = 0
      this.tableData.forEach(item => {
        area = area + Number(item.areaRatio)
      })
      if (area !== 100) {
        this.$message.warning('当前区域面积占比之和不等于100%，请重新输入')
        return
      }
      // const arr = this.tableData.filter(item => !item.id)
      this.loading = true
      this.loadingText = '系统处理中'
      this.submiting = true
      saveProportionDetail(this.tableData).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$nextTick(() => {
            this.getTableData()
          })
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.submiting = false
        this.loading = false
        this.loadingText = ''
      })
    },
    // 保存表格--修改
    saveEditRow() {
      const flag = this.tableData.some(item => !item.specialAreaType || !item.areaRatio)
      if (flag) {
        this.$message.warning('请完善表格数据')
        return
      }
      let area = 0
      this.tableData.forEach(item => {
        area = area + Number(item.areaRatio)
      })
      if (area !== 100) {
        this.$message.warning('当前区域面积占比之和不等于100%，请重新输入')
        return
      }
      this.loading = true
      this.loadingText = '系统处理中'
      putProportionDetail(this.tableData).then(res => {
        if (res.success) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getTableData()
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/ .el-breadcrumb__inner{
  color: $qup-color-primary;
}
/deep/.el-table--mini{
  border: 1px solid #EBEEF5;
}
</style>
